<template>
	<div class="breadcrumb">
		<span>空间管理</span>
	</div>
	<div>
		<div style="padding: 10px;">
			<el-button type="success" @click="createHandler">
				<el-icon><Plus /></el-icon> 添加
			</el-button>
		</div>
		<el-table :data="dataList" stripe border>
			<el-table-column prop="id" label="ID"></el-table-column>
			<el-table-column prop="name" label="名称"></el-table-column>
			<el-table-column label="操作">
				<template #default="item">
					<el-button @click="editHandler(item.row)"><el-icon><EditPen /></el-icon></el-button>
					<el-popconfirm
					 :title="removeTip"
					 confirm-button-text="确定"
					 confirm-button-type="danger"
					 cancel-button-text="取消"
					 @confirm="removeSpace(item.row)"
					>
						<template #reference>
							<el-button type="danger" @click="removeHandler(item.row)"><el-icon><Delete /></el-icon></el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
	</div>
	<el-dialog
	  v-model="dialogVisible"
	  width="300px"
	  :title="dialogTitle"
	  :show-close="false"
	>
		<el-form-item label="名称">
			<el-input v-model="space.id" type="hidden"></el-input>
			<el-input v-model="space.name" maxlength="32"></el-input>
		</el-form-item>
		<template #footer>
		    <span>
		        <el-button @click="dialogVisible = false">取消</el-button>
		        <el-button type="primary" @click="saveSpace">
		          保存
		        </el-button>
		    </span>
		</template>
	</el-dialog>
</template>

<script>
import { spaceList, saveSpace, modifySpace, removeSpace } from '@/api/space'
export default {
	name: 'SpaceList',
	data() {
		return{
			dataList: [],
			removeTip: '',
			dialogVisible: false,
			dialogTitle: '新建空间',
			space: {
				id: undefined,
				name: ''
			}
		}
	},
	methods: {
		createHandler: function(){
			this.space = {id: undefined,name:''}
			this.dialogVisible = true
			this.dialogTitle = '新建空间'
		},
		editHandler: function(item){
			this.dialogTitle = '编辑空间['+item.name+']'
			console.log(item)
			this.dialogVisible = true
			this.space = {...item}
		},
		removeHandler: function(item){
			this.removeTip = '是否删除空间['+item.name+']?'
		},
		loadSpaceList: function(){
			spaceList()
			.then(ret => {
				this.dataList = ret.data
			})
		},
		removeSpace: function(item){
			removeSpace({
				id: item.id
			}).then(res => {
				this.loadSpaceList()
			})
		},
		saveSpace: function(){
			if(this.space.id){
				modifySpace(this.space)
				.then(res => {
					this.loadSpaceList()
				})
			}else{
				saveSpace(this.space)
				.then(res => {
					this.loadSpaceList()
				})
			}
			this.dialogVisible = false
		}
	},
	mounted() {
		this.loadSpaceList()
	}
}
</script>

<style>
.breadcrumb{
	font-size: 18px;
	font-weight: bold;
	height: 40px;
}
</style>